import { useState } from 'react';
import { toast } from 'sonner';
import AdminLayout from '@/components/admin/AdminLayout';
import { useServices, useCreateService, useUpdateService, useDeleteService } from '@/hooks/useServices';
import { Service, ServiceCreate, ServiceUpdate } from '@/types';

// 服务分类选项
const serviceCategories = [
  '环境影响评价',
  '污染治理工程',
  '生态环境修复',
  '环境监测检测',
  '环保咨询服务'
];

// 可用图标列表
const availableIcons = [
  { value: 'fa-file-alt', label: '文档 (fa-file-alt)' },
  { value: 'fa-water', label: '水处理 (fa-water)' },
  { value: 'fa-leaf', label: '生态 (fa-leaf)' },
  { value: 'fa-flask', label: '检测 (fa-flask)' },
  { value: 'fa-gavel', label: '法律 (fa-gavel)' },
  { value: 'fa-recycle', label: '回收 (fa-recycle)' },
  { value: 'fa-industry', label: '工业 (fa-industry)' },
  { value: 'fa-chart-line', label: '图表 (fa-chart-line)' },
];

export default function ServiceManagement() {
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [currentService, setCurrentService] = useState<Service | null>(null);
  const [isEditing, setIsEditing] = useState(false);
  const [searchTerm, setSearchTerm] = useState('');

  // API hooks
  const { data: servicesData, isLoading, refetch } = useServices({
    active_only: false,
    size: 100 // 获取所有服务
  });
  const createServiceMutation = useCreateService();
  const updateServiceMutation = useUpdateService();
  const deleteServiceMutation = useDeleteService();

  // 表单状态
  const [formData, setFormData] = useState({
    name: '',
    description: '',
    content: '',
    icon_url: 'fa-file-alt',
    category: serviceCategories[0],
    price: '',
    features: '',
    is_active: true,
    is_featured: false,
    sort_order: 0
  });

  const services = servicesData?.items || [];

  // 筛选服务
  const filteredServices = services.filter(item =>
    item.name.toLowerCase().includes(searchTerm.toLowerCase()) ||
    (item.description && item.description.toLowerCase().includes(searchTerm.toLowerCase()))
  );

  // 重置表单
  const resetForm = () => {
    setFormData({
      name: '',
      description: '',
      content: '',
      icon_url: 'fa-file-alt',
      category: serviceCategories[0],
      price: '',
      features: '',
      is_active: true,
      is_featured: false,
      sort_order: 0
    });
  };

  // 打开添加服务模态框
  const openAddModal = () => {
    setIsEditing(false);
    setCurrentService(null);
    const newSortOrder = services.length > 0 ? Math.max(...services.map(s => s.sort_order || 0)) + 1 : 1;
    setFormData({
      name: '',
      description: '',
      content: '',
      icon_url: 'fa-file-alt',
      category: serviceCategories[0],
      price: '',
      features: '',
      is_active: true,
      is_featured: false,
      sort_order: newSortOrder
    });
    setIsModalOpen(true);
  };

  // 解析服务特点为编辑格式
  const parseFeaturesToEdit = (features?: string) => {
    if (!features) return '';
    try {
      const featuresArray = JSON.parse(features);
      return Array.isArray(featuresArray) ? featuresArray.join('\n') : features;
    } catch {
      return features;
    }
  };

  // 打开编辑服务模态框
  const openEditModal = (service: Service) => {
    setIsEditing(true);
    setCurrentService(service);
    setFormData({
      name: service.name,
      description: service.description || '',
      content: service.content || '',
      icon_url: service.icon_url || 'fa-file-alt',
      category: service.category || serviceCategories[0],
      price: service.price ? service.price.toString() : '',
      features: parseFeaturesToEdit(service.features),
      is_active: service.is_active,
      is_featured: service.is_featured || false,
      sort_order: service.sort_order || 0
    });
    setIsModalOpen(true);
  };

  // 关闭模态框
  const closeModal = () => {
    setIsModalOpen(false);
    resetForm();
  };

  // 处理表单输入变化
  const handleInputChange = (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement>) => {
    const { name, value, type } = e.target;
    const checked = (e.target as HTMLInputElement).checked;
    setFormData(prev => ({
      ...prev,
      [name]: type === 'checkbox' ? checked : value
    }));
  };

  // 处理服务特点格式
  const formatFeatures = (features: string) => {
    if (!features.trim()) return '';
    // 将每行转换为数组，然后转为JSON字符串
    const featuresArray = features.split('\n').map(f => f.trim()).filter(f => f);
    return JSON.stringify(featuresArray);
  };

  // 保存服务
  const saveService = async () => {
    if (!formData.name || !formData.description) {
      toast.error('请填写所有必填字段');
      return;
    }

    try {
      if (isEditing && currentService) {
        // 编辑现有服务
        const updateData: ServiceUpdate = {
          name: formData.name,
          description: formData.description,
          content: formData.content,
          icon_url: formData.icon_url,
          category: formData.category,
          price: formData.price ? parseFloat(formData.price) : undefined,
          features: formatFeatures(formData.features),
          is_active: formData.is_active,
          is_featured: formData.is_featured,
          sort_order: formData.sort_order
        };

        await updateServiceMutation.mutateAsync({
          id: currentService.id,
          data: updateData
        });

        toast.success('服务更新成功');
      } else {
        // 添加新服务
        const createData: ServiceCreate = {
          name: formData.name,
          description: formData.description,
          content: formData.content,
          icon_url: formData.icon_url,
          category: formData.category,
          price: formData.price ? parseFloat(formData.price) : undefined,
          features: formatFeatures(formData.features),
          is_active: formData.is_active,
          is_featured: formData.is_featured,
          sort_order: formData.sort_order
        };

        await createServiceMutation.mutateAsync(createData);
        toast.success('服务添加成功');
      }

      closeModal();
      refetch(); // 刷新数据
    } catch (error) {
      console.error('保存服务失败:', error);
      toast.error('保存失败，请重试');
    }
  };

  // 删除服务
  const deleteService = async (id: number) => {
    if (window.confirm('确定要删除这个服务项目吗？')) {
      try {
        await deleteServiceMutation.mutateAsync(id);
        toast.success('服务删除成功');
        refetch();
      } catch (error) {
        console.error('删除服务失败:', error);
        toast.error('删除失败，请重试');
      }
    }
  };

  // 切换服务状态
  const toggleServiceStatus = async (service: Service) => {
    try {
      await updateServiceMutation.mutateAsync({
        id: service.id,
        data: { is_active: !service.is_active }
      });
      toast.success(`服务已${service.is_active ? '禁用' : '启用'}`);
      refetch();
    } catch (error) {
      console.error('切换状态失败:', error);
      toast.error('操作失败，请重试');
    }
  };

  if (isLoading) {
    return (
      <AdminLayout>
        <div className="flex items-center justify-center min-h-[500px]">
          <div className="text-center">
            <i className="fa-solid fa-spinner fa-spin text-3xl text-blue-600 mb-4"></i>
            <p className="text-gray-600">加载中...</p>
          </div>
        </div>
      </AdminLayout>
    );
  }

  return (
    <AdminLayout>
      <div className="flex flex-col md:flex-row md:items-center md:justify-between mb-6">
        <div>
          <h1 className="text-2xl font-bold text-gray-800">服务管理</h1>
          <p className="text-gray-600">管理公司业务服务内容</p>
        </div>
        <button
          type="button"
          onClick={openAddModal}
          className="mt-4 md:mt-0 bg-blue-600 hover:bg-blue-700 text-white font-medium py-2 px-4 rounded-lg transition-colors flex items-center"
        >
          <i className="fa-solid fa-plus mr-2"></i> 添加服务
        </button>
      </div>

      {/* 搜索框 */}
      <div className="mb-6">
        <div className="relative">
          <i className="fa-solid fa-search absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400"></i>
          <input
            type="text"
            placeholder="搜索服务名称或描述..."
            value={searchTerm}
            onChange={(e) => setSearchTerm(e.target.value)}
            className="w-full pl-10 pr-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition-colors"
          />
          {searchTerm && (
            <button
              type="button"
              onClick={() => setSearchTerm('')}
              className="absolute right-3 top-1/2 transform -translate-y-1/2 text-gray-400 hover:text-gray-600"
              title="清除搜索"
              aria-label="清除搜索"
            >
              <i className="fa-solid fa-times"></i>
            </button>
          )}
        </div>
      </div>

      {/* 服务列表 */}
      <div className="bg-white rounded-lg shadow overflow-hidden">
        <div className="overflow-x-auto">
          <table className="min-w-full divide-y divide-gray-200">
            <thead className="bg-gray-50">
              <tr>
                <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">排序</th>
                <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">图标</th>
                <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">服务名称</th>
                <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">分类</th>
                <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">价格</th>
                <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">描述</th>
                <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">状态</th>
                <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">创建时间</th>
                <th className="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase tracking-wider">操作</th>
              </tr>
            </thead>
            <tbody className="bg-white divide-y divide-gray-200">
              {filteredServices.map((service) => (
                <tr key={service.id} className="hover:bg-gray-50 transition-colors">
                  <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                    {service.sort_order}
                  </td>
                  <td className="px-6 py-4 whitespace-nowrap">
                    <div className="w-8 h-8 bg-blue-100 rounded-full flex items-center justify-center">
                      <i className={`fa-solid ${service.icon_url} text-blue-600`}></i>
                    </div>
                  </td>
                  <td className="px-6 py-4 whitespace-nowrap">
                    <div className="text-sm font-medium text-gray-900">{service.name}</div>
                  </td>
                  <td className="px-6 py-4 whitespace-nowrap">
                    <span className="px-2 inline-flex text-xs leading-5 font-semibold rounded-full bg-blue-100 text-blue-800">
                      {service.category}
                    </span>
                  </td>
                  <td className="px-6 py-4 whitespace-nowrap">
                    <div className="text-sm text-gray-900">
                      {service.price ? `¥${service.price}` : '面议'}
                    </div>
                  </td>
                  <td className="px-6 py-4">
                    <div className="text-sm text-gray-900 max-w-xs truncate">
                      {service.description}
                    </div>
                  </td>
                  <td className="px-6 py-4 whitespace-nowrap">
                    <span
                      className={`px-2 inline-flex text-xs leading-5 font-semibold rounded-full ${
                        service.is_active
                          ? 'bg-green-100 text-green-800'
                          : 'bg-gray-100 text-gray-800'
                      }`}
                    >
                      {service.is_active ? '启用' : '禁用'}
                    </span>
                  </td>
                  <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                    {new Date(service.created_at).toLocaleDateString('zh-CN')}
                  </td>
                  <td className="px-6 py-4 whitespace-nowrap text-right text-sm font-medium">
                    <button
                      type="button"
                      onClick={() => toggleServiceStatus(service)}
                      className={`mr-3 text-sm ${
                        service.is_active
                          ? 'text-yellow-600 hover:text-yellow-900'
                          : 'text-green-600 hover:text-green-900'
                      }`}
                    >
                      {service.is_active ? '禁用' : '启用'}
                    </button>
                    <button
                      type="button"
                      onClick={() => openEditModal(service)}
                      className="text-blue-600 hover:text-blue-900 mr-3 text-sm"
                    >
                      编辑
                    </button>
                    <button
                      type="button"
                      onClick={() => deleteService(service.id)}
                      className="text-red-600 hover:text-red-900 text-sm"
                    >
                      删除
                    </button>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>

        {filteredServices.length === 0 && (
          <div className="text-center py-12">
            <i className="fa-solid fa-cogs text-gray-400 text-6xl mb-4"></i>
            <h3 className="text-xl font-semibold text-gray-900 mb-2">暂无服务</h3>
            <p className="text-gray-600">
              {searchTerm ? '没有找到匹配的服务' : '还没有添加任何服务'}
            </p>
          </div>
        )}
      </div>

      {/* 添加/编辑服务模态框 */}
      {isModalOpen && (
        <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center p-4 z-50">
          <div className="bg-white rounded-lg max-w-2xl w-full max-h-[90vh] overflow-y-auto">
            <div className="p-6">
              <div className="flex items-center justify-between mb-6">
                <h2 className="text-xl font-bold text-gray-900">
                  {isEditing ? '编辑服务' : '添加服务'}
                </h2>
                <button
                  type="button"
                  onClick={closeModal}
                  className="text-gray-400 hover:text-gray-600"
                  title="关闭"
                  aria-label="关闭模态框"
                >
                  <i className="fa-solid fa-times text-xl"></i>
                </button>
              </div>

              <form onSubmit={(e) => { e.preventDefault(); saveService(); }} className="space-y-4">
                {/* 服务名称 */}
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-2">
                    服务名称 <span className="text-red-500">*</span>
                  </label>
                  <input
                    type="text"
                    name="name"
                    value={formData.name}
                    onChange={handleInputChange}
                    className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                    placeholder="请输入服务名称"
                    required
                  />
                </div>

                {/* 服务分类 */}
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-2">
                    服务分类
                  </label>
                  <select
                    name="category"
                    value={formData.category}
                    onChange={handleInputChange}
                    className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                    title="选择服务分类"
                    aria-label="服务分类"
                  >
                    {serviceCategories.map((category) => (
                      <option key={category} value={category}>
                        {category}
                      </option>
                    ))}
                  </select>
                </div>

                {/* 服务图标 */}
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-2">
                    服务图标
                  </label>
                  <select
                    name="icon_url"
                    value={formData.icon_url}
                    onChange={handleInputChange}
                    className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                    title="选择服务图标"
                    aria-label="服务图标"
                  >
                    {availableIcons.map((icon) => (
                      <option key={icon.value} value={icon.value}>
                        {icon.label}
                      </option>
                    ))}
                  </select>
                  <div className="mt-2 flex items-center">
                    <span className="text-sm text-gray-500 mr-2">预览:</span>
                    <div className="w-8 h-8 bg-blue-100 rounded-full flex items-center justify-center">
                      <i className={`fa-solid ${formData.icon_url} text-blue-600`}></i>
                    </div>
                  </div>
                </div>

                {/* 服务描述 */}
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-2">
                    服务描述 <span className="text-red-500">*</span>
                  </label>
                  <textarea
                    name="description"
                    value={formData.description}
                    onChange={handleInputChange}
                    rows={3}
                    className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                    placeholder="请输入服务描述"
                    required
                  />
                </div>

                {/* 详细内容 */}
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-2">
                    详细内容
                  </label>
                  <textarea
                    name="content"
                    value={formData.content}
                    onChange={handleInputChange}
                    rows={5}
                    className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                    placeholder="请输入详细内容（可选）"
                  />
                </div>

                {/* 服务价格 */}
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-2">
                    服务价格（元）
                  </label>
                  <input
                    type="number"
                    name="price"
                    value={formData.price}
                    onChange={handleInputChange}
                    min="0"
                    step="0.01"
                    className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                    placeholder="请输入服务价格（可选，留空表示面议）"
                  />
                </div>

                {/* 服务特点 */}
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-2">
                    服务特点
                  </label>
                  <textarea
                    name="features"
                    value={formData.features}
                    onChange={handleInputChange}
                    rows={4}
                    className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                    placeholder="请输入服务特点，每行一个特点，例如：&#10;专业团队&#10;快速响应&#10;合规保证"
                  />
                  <p className="mt-1 text-sm text-gray-500">
                    每行输入一个特点，将在前台以列表形式显示
                  </p>
                </div>

                {/* 排序顺序 */}
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-2">
                    排序顺序
                  </label>
                  <input
                    type="number"
                    name="sort_order"
                    value={formData.sort_order}
                    onChange={handleInputChange}
                    min="0"
                    className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                    placeholder="排序顺序（数字越小越靠前）"
                  />
                </div>

                {/* 状态选项 */}
                <div className="space-y-3">
                  <div className="flex items-center">
                    <input
                      type="checkbox"
                      id="is_active"
                      name="is_active"
                      checked={formData.is_active}
                      onChange={handleInputChange}
                      className="h-4 w-4 text-blue-600 focus:ring-blue-500 border-gray-300 rounded"
                    />
                    <label htmlFor="is_active" className="ml-2 block text-sm text-gray-900">
                      启用服务
                    </label>
                  </div>

                  <div className="flex items-center">
                    <input
                      type="checkbox"
                      id="is_featured"
                      name="is_featured"
                      checked={formData.is_featured}
                      onChange={handleInputChange}
                      className="h-4 w-4 text-blue-600 focus:ring-blue-500 border-gray-300 rounded"
                    />
                    <label htmlFor="is_featured" className="ml-2 block text-sm text-gray-900">
                      推荐服务
                    </label>
                  </div>
                </div>

                {/* 按钮 */}
                <div className="flex justify-end space-x-3 pt-6">
                  <button
                    type="button"
                    onClick={closeModal}
                    className="px-4 py-2 border border-gray-300 rounded-lg text-gray-700 hover:bg-gray-50 transition-colors"
                  >
                    取消
                  </button>
                  <button
                    type="submit"
                    disabled={createServiceMutation.isPending || updateServiceMutation.isPending}
                    className="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors disabled:opacity-50 disabled:cursor-not-allowed flex items-center"
                  >
                    {(createServiceMutation.isPending || updateServiceMutation.isPending) && (
                      <i className="fa-solid fa-spinner fa-spin mr-2"></i>
                    )}
                    {isEditing ? '更新' : '添加'}
                  </button>
                </div>
              </form>
            </div>
          </div>
        </div>
      )}
    </AdminLayout>
  );
}